import React, { useState, useEffect, useRef } from 'react';
import Login from './components/Login';
import UserList from './components/UserList';
import ChatWindow from './components/ChatWindow';

/**
 * 消息接口定义
 * @interface Message
 * @property {number} id - 消息ID
 * @property {string} type - 消息类型
 * @property {string} from - 发送者
 * @property {string} to - 接收者
 * @property {string} content - 消息内容
 * @property {string} timestamp - 时间戳
 */
export interface Message {
  id: number;
  type: string;
  from: string;
  to: string;
  content: string;
  timestamp: string;
}

/**
 * WebSocket消息接口定义
 * @interface WebSocketMessage
 * @property {string} type - 消息类型
 * @property {string} [username] - 用户名（用于登录）
 * @property {string[]} [users] - 在线用户列表
 * @property {Message[]} [messages] - 消息列表
 * @property {string} [content] - 消息内容
 * @property {string} [from] - 发送者
 * @property {string} [to] - 接收者
 * @property {string} [timestamp] - 时间戳
 * @property {string} [withUser] - 目标用户（用于获取历史消息）
 */
export interface WebSocketMessage {
  type: string;
  username?: string;
  users?: string[];
  messages?: Message[];
  content?: string;
  from?: string;
  to?: string;
  timestamp?: string;
  withUser?: string;
}

const App: React.FC = () => {
  const [currentUser, setCurrentUser] = useState<string>('');
  const [onlineUsers, setOnlineUsers] = useState<string[]>([]);
  const [selectedUser, setSelectedUser] = useState<string>('');
  const [messages, setMessages] = useState<Message[]>([]);
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const ws = useRef<WebSocket | null>(null);

  useEffect(() => {
    if (currentUser) {
      connectWebSocket();
    }

    return () => {
      if (ws.current) {
        ws.current.close();
      }
    };
  }, [currentUser]);

  // 建立WebSocket连接并设置事件处理器
  const connectWebSocket = () => {
    // 创建WebSocket连接，连接到后端服务器
    const socket = new WebSocket('ws://localhost:3001');
    ws.current = socket;

    // WebSocket连接打开事件：连接成功建立时触发
    socket.onopen = () => {
      console.log('WebSocket连接已建立');
      setIsConnected(true);
      
      // 发送登录消息
      const loginMessage: WebSocketMessage = {
        type: 'login',
        username: currentUser
      };
      socket.send(JSON.stringify(loginMessage));
    };

    // WebSocket消息接收事件：处理从服务器接收的消息
    socket.onmessage = (event) => {
      try {
        const data: WebSocketMessage = JSON.parse(event.data);
        handleWebSocketMessage(data);
      } catch (error) {
        console.error('解析WebSocket消息错误:', error);
      }
    };

    // WebSocket连接关闭事件：连接断开时触发
    socket.onclose = () => {
      console.log('WebSocket连接已关闭');
      setIsConnected(false);
    };

    // WebSocket错误事件：处理连接错误
    socket.onerror = (error) => {
      console.error('WebSocket错误:', error);
      setIsConnected(false);
    };
  };

  // 处理从WebSocket接收的消息，根据消息类型进行相应处理
  const handleWebSocketMessage = (data: WebSocketMessage) => {
    switch (data.type) {
      case 'login_success':
        console.log('登录成功');
        break;
      case 'user_list':
        if (data.users) {
          setOnlineUsers(data.users.filter(user => user !== currentUser));
        }
        break;
      case 'message':
        if (data.from && data.content && data.timestamp) {
          const newMessage: Message = {
            id: Date.now(),
            type: 'message',
            from: data.from,
            to: currentUser,
            content: data.content,
            timestamp: data.timestamp
          };
          setMessages(prev => [...prev, newMessage]);
        }
        break;
      case 'history':
        if (data.messages) {
          setMessages(data.messages);
        }
        break;
      case 'error':
        console.error('服务器错误:', data.content);
        break;
      default:
        console.log('未知消息类型:', data.type);
    }
  };

  const handleLogin = (username: string) => {
    setCurrentUser(username);
  };

  const handleUserSelect = (username: string) => {
    setSelectedUser(username);
    setMessages([]);
    
    // 请求历史消息
    if (ws.current && ws.current.readyState === WebSocket.OPEN) {
      const historyMessage: WebSocketMessage = {
        type: 'get_history',
        withUser: username
      };
      ws.current.send(JSON.stringify(historyMessage));
    }
  };

  /**
 * 处理发送消息到选中的用户
 * @param content 消息内容
 */
const handleSendMessage = (content: string) => {
    if (!content.trim() || !selectedUser || !ws.current) return;

    const message: WebSocketMessage = {
      type: 'message',
      to: selectedUser,
      content: content.trim()
    };

    ws.current.send(JSON.stringify(message));
  };

  const handleLogout = () => {
    if (ws.current) {
      ws.current.close();
    }
    setCurrentUser('');
    setOnlineUsers([]);
    setSelectedUser('');
    setMessages([]);
    setIsConnected(false);
  };

  if (!currentUser) {
    return <Login onLogin={handleLogin} />;
  }

  return (
    <div className="chat-layout">
      <UserList
        currentUser={currentUser}
        onlineUsers={onlineUsers}
        selectedUser={selectedUser}
        onUserSelect={handleUserSelect}
        onLogout={handleLogout}
        isConnected={isConnected}
      />
      <ChatWindow
        currentUser={currentUser}
        selectedUser={selectedUser}
        messages={messages}
        onSendMessage={handleSendMessage}
        isConnected={isConnected}
      />
    </div>
  );
};

export default App;